package com.atjinggu.jinggumail.product.service.impl;

import com.atjinggu.jinggumail.common.constant.ProductConstant;
import com.atjinggu.jinggumail.product.dao.AttrAttrgroupRelationDao;
import com.atjinggu.jinggumail.product.dao.AttrGroupDao;
import com.atjinggu.jinggumail.product.dao.CategoryDao;
import com.atjinggu.jinggumail.product.entity.AttrAttrgroupRelationEntity;
import com.atjinggu.jinggumail.product.entity.AttrGroupEntity;
import com.atjinggu.jinggumail.product.entity.CategoryEntity;
import com.atjinggu.jinggumail.product.service.CategoryService;
import com.atjinggu.jinggumail.product.vo.AttrVo;
import com.atjinggu.jinggumail.product.vo.RespAttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atjinggu.jinggumail.common.utils.PageUtils;
import com.atjinggu.jinggumail.common.utils.Query;

import com.atjinggu.jinggumail.product.dao.AttrDao;
import com.atjinggu.jinggumail.product.entity.AttrEntity;
import com.atjinggu.jinggumail.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), new QueryWrapper<AttrEntity>());

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr,entity);
        //保存本身信息
        this.save(entity);
        //保存属性和属性分组关联关系
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrId(entity.getAttrId());
        attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
        attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);

    }

    @Override
    public PageUtils queryAttrList(Map<String, Object> params, Integer categoryId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode(): ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(categoryId != 0){
                 wrapper.eq("catelog_id",categoryId);
        }
        String key = (String) params.get("key");
        if(StringUtils.isNotBlank(key)){
            wrapper.and(w -> {
               w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        List<AttrEntity> entities = page.getRecords();
        List<RespAttrVo> respAttrVos = entities.stream().map(entity -> {
            RespAttrVo respAttrVo = new RespAttrVo();
            BeanUtils.copyProperties(entity,respAttrVo);
            CategoryEntity categoryEntity = categoryDao.selectOne(new QueryWrapper<CategoryEntity>().eq("cat_id",entity.getCatelogId()));
            if(null != categoryEntity) {
                respAttrVo.setCatelogName(categoryEntity.getName());
            }

            AttrAttrgroupRelationEntity attrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", entity.getAttrId()));
            if(attrgroupRelationEntity != null){
                AttrGroupEntity attrGroup = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", attrgroupRelationEntity.getAttrGroupId()));
                if(attrGroup != null){
                    respAttrVo.setGroupName(attrGroup.getAttrGroupName());
                }
            }
            return respAttrVo;
        }).collect(Collectors.toList());
        PageUtils pageUtils =    new PageUtils(page);
        pageUtils.setList(respAttrVos);
        return pageUtils;
    }

    @Override
    public RespAttrVo getDetailById(Long attrId) {
        RespAttrVo respAttrVo = new RespAttrVo();
        AttrEntity attr = this.getById(attrId);
        BeanUtils.copyProperties(attr,respAttrVo);
        //查询分类信息
        Long[] paths = categoryService.getPaths(attr.getCatelogId());
        respAttrVo.setCateLogIds(paths);
        //查询分组信息
        AttrAttrgroupRelationEntity attrgroupRelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if(attrgroupRelation!= null){
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelation.getAttrGroupId());
            if(attrGroupEntity != null){
                respAttrVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
                respAttrVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
        return respAttrVo;
    }

    @Override
    public void updateAttrById(RespAttrVo attrVo) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,entity);
        //修改自身
        this.updateById(entity);

        //修改属性和属性分组关联关系
        AttrAttrgroupRelationEntity attrgroupRelation= new AttrAttrgroupRelationEntity();
        attrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());
        attrgroupRelation.setAttrId(attrVo.getAttrId());

        Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
        //已经有，则修改，没有，则新增
        if(count > 0){
            attrAttrgroupRelationDao.update(attrgroupRelation,new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
        }else{
            attrAttrgroupRelationDao.insert(attrgroupRelation);
        }

    }

    /**
     * 根据分组id查找关联的所有基本属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if(attrIds == null || attrIds.size() == 0){
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }


}